﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Threading;


/// <summary>
/// Summary description for LogHelper
/// </summary>
namespace GDBLL.Log
{
    public class ThreadLogProvider : ILogProvider
    {
        private string s_path = string.Empty;

        private List<LogMessage> _dic = new List<LogMessage>();

        private object state = new object();

        public ThreadLogProvider(string path)
        {
            s_path = path;
            Thread t = new Thread(new ThreadStart(WriteLog_WaitCallback));
            t.IsBackground = false;
            t.Start();
        }

        public void WriteLog(string msg)
        {
            LogMessage logMsg = new LogMessage(msg, "Default", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            WriteLog(logMsg);
        }

        public void WriteLog(string msg, string type)
        {
            LogMessage logMsg = new LogMessage(msg, type, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            WriteLog(logMsg);
        }

        public void WriteLog(string msg,string type,string date)
        {
            LogMessage logMsg = new LogMessage(msg, type, date);
            WriteLog(logMsg);
        }

        private void WriteLog(LogMessage logMsg)
        {
            if (logMsg != null)
            {
                _dic.Add(logMsg);
            }
        }

        private void WriteLog_WaitCallback()
        {
            while (true)
            {
                LogMessage[] m_dic;

                lock (state)
                {
                    m_dic = _dic.ToArray();
                    _dic.Clear();
                }

                if (m_dic.Length == 0)
                {
                    Thread.Sleep(3000);
                }
                else
                {

                    foreach (LogMessage item in m_dic)
                    {
                        DateTime dt = DateTime.Today;
                        if (!Directory.Exists(s_path))
                        {
                            Directory.CreateDirectory(s_path);
                        }

                        String filePath = Path.Combine(s_path, dt.ToString("yyyyMMdd") + "." + item.Type + ".log");
                        using (StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
                        {
                            sw.WriteLine(String.Format("{0}:{1}", item.Date, item.Message));
                        }

                        //Thread.Sleep(30);
                    }
                }
            }
        }

    }
}

